//
//  DASearchBookTypeAndHotBookViewController.m
//  DAKnowledge
//
//  Created by DreamArts on 16/5/24.
//  Copyright © 2016年 lidongyang. All rights reserved.
//

#import "DASearchBookTypeAndHotBookViewController.h"
#import "DABookTypeTableViewCell.h"
#import "DASearchBookTableViewCell.h"
#import "DABookType.h"
#import "DAHotBookModel.h"
#import "DAHotBookTableViewCell.h"
#import "DASearchBookViewController.h"
#import "DASearchBookDetailViewController.h"
#import "DASearchBookModel.h"
#import "DAFindBookTableViewCell.h"
@interface DASearchBookTypeAndHotBookViewController ()<UITableViewDataSource, UITableViewDelegate, UISearchBarDelegate, UISearchDisplayDelegate>{
    UIView *statusCover;
}
@property (weak, nonatomic) IBOutlet UIView *searchBarBackView;
@property (weak, nonatomic) IBOutlet UISearchBar *search;
@property (weak, nonatomic) IBOutlet UITableView *tableView;
@property (nonatomic, strong) NSMutableArray *typeArray;
@property (nonatomic, strong) NSMutableArray *hotBookArray;
@property (nonatomic, strong) NSMutableArray *searchBookArray;
@property (nonatomic, strong) NSArray *sectionTitleArray;
@property (strong, nonatomic) IBOutlet UISearchDisplayController *UISearchDisplayController;


@property (nonatomic, strong) MJRefreshAutoNormalFooter *footer;


@property (nonatomic) BOOL isRefresh;



@property (nonatomic, strong) UISearchController *searchController;

@property (nonatomic, assign) NSInteger pageNumber;
@end

@implementation DASearchBookTypeAndHotBookViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    [self searchSetting];
    [self tableViewSetting];
    [self prepareData];
   // [self prepareDataSearchBook];
    // 注册通知
    NSNotificationCenter *center = [NSNotificationCenter defaultCenter];
    [center addObserver:self selector:@selector(disMissViewController) name:@"back" object:nil];
    self.pageNumber = 0;
    self.isRefresh = YES;
}
// 移除通知
- (void)dealloc{
    [[NSNotificationCenter defaultCenter]removeObserver:self name:@"back" object:nil];
}
#pragma mark - searchBar设置
- (void)searchSetting{
    NSString *input = NSLocalizedString(@"InputBookNameForSearch", nil);
    
    self.search.backgroundImage = [self imageWithColor:[UIColor clearColor] size:self.search.bounds.size];
    self.search.placeholder = input;
    self.search.delegate = self;
    self.UISearchDisplayController.delegate = self;
    // self.tableView.tableHeaderView = self.search;
    UITextField *text = [self.search valueForKey:@"_searchField"];
    [text setValue:[UIFont systemFontOfSize:12] forKeyPath:@"_placeholderLabel.font"];
    self.searchBarBackView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    [self.search setTintColor:[UIColor whiteColor]];
    [[[[self.searchDisplayController.searchBar.subviews objectAtIndex:0] subviews] objectAtIndex:0] removeFromSuperview];
}
- (void)searchBarTextDidBeginEditing:(UISearchBar *)searchBar{
    [self.searchDisplayController.searchBar setBackgroundColor:[UIColor supportGreenColor]];
    statusCover = [[UIView alloc]initWithFrame:CGRectMake(0, 0, SCREENWIDTH, 20)];
    statusCover.backgroundColor = [UIColor supportGreenColor];
    [self.view addSubview:statusCover];
    [self.search setTintColor:[UIColor whiteColor]];
}
- (void)searchBarTextDidEndEditing:(UISearchBar *)searchBar{
    [self.searchDisplayController.searchBar setBackgroundColor:[UIColor colorWithHexString:backGroundColor]];
    [statusCover removeFromSuperview];
    [self.search setTintColor:[UIColor darkGrayColor]];
}
- (void)searchBarSearchButtonClicked:(UISearchBar *)searchBar{
    NSLog(@"搜索");
    [self prepareDataSearchBook];
}
//- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
//  
//}
#pragma mark -tableView 设置
- (void)tableViewSetting{
    self.tableView.delegate = self;
    self.tableView.dataSource = self;
    self.tableView.tableFooterView = [[UIView alloc] init];
     self.searchDisplayController.searchResultsTableView.tableFooterView = [[UIView alloc]init];
    self.tableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    NSString *hotBook = NSLocalizedString(@"hotBook", nil);
    
    self.sectionTitleArray = @[@"图书分类", hotBook];
    self.searchDisplayController.searchResultsTableView.backgroundColor = [UIColor colorWithHexString:backGroundColor];
    // 注册searchDisplayController tableViewCell
    [self.searchDisplayController.searchResultsTableView registerClass:[DAFindBookTableViewCell class] forCellReuseIdentifier:@"findBook"];
//    // 上拉
    self.footer = [MJRefreshAutoNormalFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMoreData)];
    
    self.searchDisplayController.searchResultsTableView.mj_footer = self.footer;
    self.searchDisplayController.searchResultsTableView.mj_footer.hidden = YES;
    
//    MJRefreshGifHeader *header =[MJRefreshGifHeader headerWithRefreshingTarget:self refreshingAction:@selector(refreshData)];
//    NSMutableArray *refreshImages = [[NSMutableArray alloc] init];
//    for (NSUInteger i = 1; i<=21; i++) {
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"page%ld", i]];
//        [refreshImages addObject:image];
//    }
//    NSMutableArray *normalImages = [[NSMutableArray alloc] init];
//    for (NSUInteger i = 1; i<=21; i++) {
//        UIImage *image = [UIImage imageNamed:[NSString stringWithFormat:@"stay%ld", i]];
//        [normalImages addObject:image];
//    }
//    UIImage *image = [UIImage imageNamed:@"stay21"];
//    [normalImages insertObject:image atIndex:0];
//    
//    [header setImages:refreshImages duration:0.5 forState:MJRefreshStateRefreshing];
//    [header setImages:normalImages forState:MJRefreshStateIdle];
//    [header setImages:refreshImages duration:0.5 forState:MJRefreshStatePulling];
//    
//    header.lastUpdatedTimeLabel.hidden= YES;//如果不隐藏这个会默认 图片在最左边不是在中间
//    header.stateLabel.hidden = YES;
//    //self.tableView.mj_header = header;
//    self.searchDisplayController.searchResultsTableView.mj_header = header;
}
- (void)refreshData{
    self.pageNumber = 0;
    self.isRefresh = YES;
    [self prepareDataSearchBook];
}
- (void)loadMoreData{
    self.isRefresh = NO;
    [self prepareDataSearchBook];
}
#pragma mark - 图书搜索
- (void)prepareDataSearchBook{
    NSString *url = DASearchBookURL;
    NSString *pageNumber = [NSString stringWithFormat:@"%ld", self.pageNumber];
    NSDictionary *dic = @{@"keyword": self.search.text,
                          @"page": pageNumber};
    NSLog(@"%ld", self.pageNumber);
    [SVProgressHUD show];
    [DADataHandel postURL:url parame:dic cookie:nil result:^(id result) {
        if ([result[@"result"] isKindOfClass:[NSArray class]]) {
            if ([result[@"result"] count] > 0) {
                [self dataTransformModel:result[@"result"]];
                self.pageNumber++;
            }else{
                [self.searchDisplayController.searchResultsTableView.mj_footer endRefreshing];
                NSLog(@"没有更多数据");
            }
            
            if ([result[@"result"] count] < 20) {
               // self.footer.stateLabel.hidden = YES;
                self.searchDisplayController.searchResultsTableView.mj_footer.hidden = YES;
            }else{
               // self.footer.stateLabel.hidden = NO;
                self.searchDisplayController.searchResultsTableView.mj_footer.hidden = NO;
            }
            [self finishLoadDataMBProgress];
            
        }else{
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
            }
        }
        NSLog(@"result %d", result == nil);
        for (UIView *subView in self.searchDisplayController.searchResultsTableView.subviews) {
            if ([subView isKindOfClass:NSClassFromString(@"UILabel")]) {
                UILabel *label =(UILabel *)subView;
                NSString *str = NSLocalizedString(@"No result", nil);
                label.text = [NSString stringWithFormat:@"%@",str];
            }
        }
    }];
   
}
#pragma mark - Model转化
- (void)dataTransformModel:(NSArray *)dataArray{
    DASearchBookModel  *searchBookModel = [[DASearchBookModel alloc]init];
    NSArray *array = [searchBookModel returnModelInArrayWithDic:dataArray];
    if (self.isRefresh) {
        self.searchBookArray = [NSMutableArray array];
        [self.searchBookArray addObjectsFromArray:array];
        [self.searchDisplayController.searchResultsTableView reloadData];
        [self.searchDisplayController.searchResultsTableView.mj_header endRefreshing];
    }else{
        [self.searchBookArray addObjectsFromArray:array];
        [self.searchDisplayController.searchResultsTableView.mj_footer endRefreshing];
    }
    [self finishLoadDataMBProgress];
}
- (BOOL)searchBarShouldBeginEditing:(UISearchBar *)searchBar{
    self.pageNumber = 0;
    self.isRefresh = YES;
    NSLog(@"%ld", self.pageNumber);
    [self.searchBookArray removeAllObjects];
    return YES;
}
#pragma mark - 数据准备
- (void)prepareData{
    /** 取出图书所有类型*/
    NSString *URL= DABookTypeURL;
    NSString *isLoading = NSLocalizedString(@"isLoading", nil);
    [SVProgressHUD showWithStatus:isLoading];
    [DADataHandel postURL:URL parame:nil cookie:nil result:^(id result) {
        if ([result[@"result"] isKindOfClass:[NSArray class]]) {
            if ([result[@"result"] isKindOfClass:[NSArray class]]) {
                // 图书类型
                DABookType *bookTypeModel = [[DABookType alloc]init];
                self.typeArray = [bookTypeModel returnModelInArrayWithDic:result[@"result"]];
            }
            if ([result[@"result"] isKindOfClass:[NSArray class]]) {
                // 热门图书
                DAHotBookModel *hotBookModel = [[DAHotBookModel alloc]init];
                self.hotBookArray = [hotBookModel returnModelInArrayWithDic:result[@"result2"]];
            }
            [self.tableView reloadData];
            [self finishLoadDataMBProgress];
        } else {
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.requestTimeOut]) {
                [SVProgressHUD showErrorWithStatus:self.requestTimeOut];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netIsNotAvailabel]) {
                [SVProgressHUD showErrorWithStatus:self.netIsNotAvailabel];
            }
            if ([result[@"result"] isKindOfClass:[NSString class]] && [result[@"result"] isEqualToString:self.netWorkPortConnection]) {
                [SVProgressHUD showErrorWithStatus:self.netWorkPortConnection];
            }
            
            NSLog(@"DABookTypeURL:数据异常。");
        }
    }];
}
#pragma mark - tableView dataSource
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    if (tableView == self.tableView) {
        return 2;
    }else{
        return 1;
    }
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        if (section == 0) {
            return self.typeArray.count;
        }else{
            return self.hotBookArray.count;
        }
    }else{
        return self.searchBookArray.count;
    }
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    
    if (tableView == self.tableView) {
        if (indexPath.section == 0) {
            DABookTypeTableViewCell *bookType = [tableView dequeueReusableCellWithIdentifier:@"booktype"];
           // bookType.textLabel.text = [[self.typeArray[indexPath.row] bookTypeName] stringByAppendingString:[NSString stringWithFormat:@"(%@)",[self.typeArray[indexPath.row] bookTypeNum]]];
            bookType.contentLabel.text = [[self.typeArray[indexPath.row] bookTypeName] stringByAppendingString:[NSString stringWithFormat:@"(%@)",[self.typeArray[indexPath.row] bookTypeNum]]];
            bookType.contentLabel.font = [UIFont systemFontOfSize:14];
           // bookType.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return bookType;
        }else {
            DAHotBookTableViewCell *hotBook = [tableView dequeueReusableCellWithIdentifier:@"hotBook"];
            hotBook.hotModel = self.hotBookArray[indexPath.row];
           // hotBook.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
            return hotBook;
        }
        
    }else{
        DAFindBookTableViewCell *cell = [self.tableView dequeueReusableCellWithIdentifier:@"findBook"];
        if (self.searchBookArray.count > 0) {
            cell.searchModel = self.searchBookArray[indexPath.row];
        }
       // cell.accessoryType = UITableViewCellAccessoryDisclosureIndicator;
        return cell;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView) {
        if (indexPath.section == 0) {
            return 60;
        }else{
        return 100;
        }
    }else{
        return 100;
    }

}
- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        if (section == 1) {
            UIView *view = [[UIView alloc]init];
            UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake(15, 5, self.view.frame.size.width, 30)];
            label.font = [UIFont systemFontOfSize:14];
            [view addSubview:label];
            if (self.hotBookArray.count > 0) {
                label.text = self.sectionTitleArray[section];
            }
            return view;
        }else{
            return nil;
        }
    }else{
        return nil;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        if (section == 1) {
            return 40;
        } else{
            return 0.001;
        }
    }else{
        return 0.01;
    }
    
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section{
    if (tableView == self.tableView) {
        return 0.01;
    }else{
        return 0.01;
    }
    
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    if (tableView == self.tableView) {
        if (indexPath.section == 0) {
            DASearchBookViewController * search =[self.storyboard instantiateViewControllerWithIdentifier:@"search"];
            search.typeID = [self.typeArray[indexPath.row] bookTypeId];
            [self.navigationController pushViewController:search animated:YES];
        }
        if (indexPath.section == 1) {
            DASearchBookDetailViewController *searchDetail = [self.storyboard instantiateViewControllerWithIdentifier:@"SEARCHBOOKDETAIL"];
            searchDetail.bookID = [self.hotBookArray[indexPath.row] bookID];
            searchDetail.isHomePageEnter = YES;
            [self.navigationController pushViewController:searchDetail animated:YES];
        }
    }else{
        DASearchBookDetailViewController *searchDetail = [self.storyboard instantiateViewControllerWithIdentifier:@"SEARCHBOOKDETAIL"];
        searchDetail.bookID = [self.searchBookArray[indexPath.row] bookID];
        searchDetail.isHomePageEnter = YES;
        [self.navigationController pushViewController:searchDetail animated:YES];
    }
     //cell 返回时 取消选中状态
      [tableView deselectRowAtIndexPath:indexPath animated:YES];
}
- (void)disMissViewController{
    [self.navigationController dismissViewControllerAnimated:YES completion:nil];
}
#pragma mark - searchBar背景颜色
- (UIImage *)imageWithColor:(UIColor *)color size:(CGSize)size {
    CGRect rect = CGRectMake(0, 0, size.width, size.height);
    UIGraphicsBeginImageContext(rect.size);
    CGContextRef context = UIGraphicsGetCurrentContext();
    CGContextSetFillColorWithColor(context, [color CGColor]);
    CGContextFillRect(context, rect);
    UIImage *image = UIGraphicsGetImageFromCurrentImageContext();
    UIGraphicsEndImageContext();
    return image;
}


#pragma mark - 解决UISearchDisplayController searchResultsTableView 的ContentSize bug
- (void)searchDisplayController:(UISearchDisplayController *)controller willShowSearchResultsTableView:(UITableView *)tableView{
    [tableView setContentInset:UIEdgeInsetsZero];
    [tableView setScrollIndicatorInsets:UIEdgeInsetsZero];
}

- (void)searchBar:(UISearchBar *)searchBar textDidChange:(NSString *)searchText{
    for (UIView *subView in self.searchDisplayController.searchResultsTableView.subviews) {
        if ([subView isKindOfClass:NSClassFromString(@"UILabel")]) {
            UILabel *label =(UILabel *)subView;
            label.text = @"";
        }
    }
}



- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
